package com.dk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dk.mapper.PersonRoleMapper;
import com.dk.mapper.RoleMenuMapper;
import com.dk.mapper.TRoleMapper;;
import com.dk.pojo.RoleMenuExample;
import com.dk.pojo.TRole;
import com.dk.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@org.springframework.stereotype.Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private TRoleMapper tRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private PersonRoleMapper personRoleMapper;


    @Override
    @Transactional
    public List<TRole> getInfo() {
        return tRoleMapper.selectByExample(null);
    }

    @Override
    @Transactional
    public int insert(TRole role,Integer[] nodesIds) {
        try {
            tRoleMapper.insertInfo(role) ;
            Integer roleId = role.getRoleId();
            roleMenuMapper.insertMenuinfo(roleId,nodesIds);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 1;
        }

    }

    @Override
    @Transactional
    public TRole selectById(Integer id) {
        return tRoleMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public int updateInfo(TRole tRole,Integer[] nodesIds) {
        try{
            tRoleMapper.updateByPrimaryKeySelective(tRole);
            RoleMenuExample rm = new RoleMenuExample();
            RoleMenuExample.Criteria criteria = rm.createCriteria();
            criteria.andIdEqualTo(tRole.getRoleId());
            roleMenuMapper.deleteByExample(rm);
            roleMenuMapper.insertMenuinfo(tRole.getRoleId(),nodesIds);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<Integer> selectPersonRoleByPid(Integer id) {
        return personRoleMapper.selectPersonRoleByPid(id);
    }

    @Override
    @Transactional
    public int deleteById(Integer roleId) {
        try{
            tRoleMapper.deleteByPrimaryKey(roleId);
            RoleMenuExample re = new RoleMenuExample();
            RoleMenuExample.Criteria criteria = re.createCriteria();
            criteria.andIdEqualTo(roleId);
            roleMenuMapper.deleteByExample(re);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

    }
}
